import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:netflix_social/models/social_post.dart';
import 'package:netflix_social/theme/app_theme.dart';

class SocialPostCard extends StatelessWidget {
  final SocialPost post;
  final VoidCallback onTap;
  final VoidCallback? onVideoTap;
  final VoidCallback onLikeTap;
  final VoidCallback onCommentTap;
  final VoidCallback onShareTap;

  const SocialPostCard({
    Key? key,
    required this.post,
    required this.onTap,
    this.onVideoTap,
    required this.onLikeTap,
    required this.onCommentTap,
    required this.onShareTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      color: AppTheme.cardColor,
      margin: const EdgeInsets.only(bottom: 12, left: 16, right: 16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户信息
              _buildUserInfo(context),
              
              // 帖子内容
              const SizedBox(height: 12),
              Text(post.content),
              
              // 图片（如果有）
              if (post.images.isNotEmpty) ...[
                const SizedBox(height: 12),
                _buildImageGallery(),
              ],
              
              // 关联视频（如果有）
              if (post.relatedVideo != null) ...[
                const SizedBox(height: 12),
                _buildRelatedVideo(context),
              ],
              
              // 互动信息和按钮
              const SizedBox(height: 16),
              _buildInteractionInfo(context),
              const SizedBox(height: 12),
              _buildActionButtons(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context) {
    return Row(
      children: [
        // 头像
        CircleAvatar(
          radius: 20,
          backgroundImage: CachedNetworkImageProvider(post.author.avatar),
        ),
        const SizedBox(width: 12),
        // 用户名和发布时间
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                post.author.username,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                '${post.createdAt.day}/${post.createdAt.month}/${post.createdAt.year} ${post.createdAt.hour}:${post.createdAt.minute.toString().padLeft(2, '0')}',
                style: TextStyle(
                  color: Colors.grey[500],
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
        // 菜单按钮
        IconButton(
          icon: const Icon(
            Icons.more_horiz,
            color: Colors.grey,
          ),
          onPressed: () {
            _showPostOptionsDialog(context);
          },
        ),
      ],
    );
  }

  Widget _buildImageGallery() {
    // 根据图片数量决定布局
    if (post.images.length == 1) {
      // 单张图片
      return ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: CachedNetworkImage(
          imageUrl: post.images.first,
          fit: BoxFit.cover,
          height: 200,
          width: double.infinity,
          placeholder: (context, url) => Container(
            color: Colors.grey[800],
            height: 200,
            child: const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
              ),
            ),
          ),
          errorWidget: (context, url, error) => Container(
            color: Colors.grey[800],
            height: 200,
            child: const Center(
              child: Icon(Icons.error, color: Colors.white),
            ),
          ),
        ),
      );
    } else {
      // 多张图片
      return SizedBox(
        height: 120,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: post.images.length,
          itemBuilder: (context, index) {
            return Container(
              width: 120,
              margin: const EdgeInsets.only(right: 8),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: CachedNetworkImage(
                  imageUrl: post.images[index],
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Container(
                    color: Colors.grey[800],
                    child: const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
                        strokeWidth: 2,
                      ),
                    ),
                  ),
                  errorWidget: (context, url, error) => Container(
                    color: Colors.grey[800],
                    child: const Center(
                      child: Icon(Icons.error, color: Colors.white, size: 24),
                    ),
                  ),
                ),
              ),
            );
          },
        ),
      );
    }
  }

  Widget _buildRelatedVideo(BuildContext context) {
    final video = post.relatedVideo!;
    
    return InkWell(
      onTap: onVideoTap,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[850],
          borderRadius: BorderRadius.circular(8),
        ),
        padding: const EdgeInsets.all(12),
        child: Row(
          children: [
            // 视频缩略图
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CachedNetworkImage(
                imageUrl: video.thumbnailUrl,
                width: 80,
                height: 45,
                fit: BoxFit.cover,
                placeholder: (context, url) => Container(
                  color: Colors.grey[800],
                  width: 80,
                  height: 45,
                ),
                errorWidget: (context, url, error) => Container(
                  color: Colors.grey[800],
                  width: 80,
                  height: 45,
                  child: const Icon(Icons.error, color: Colors.white, size: 20),
                ),
              ),
            ),
            const SizedBox(width: 12),
            // 视频信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    video.title,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${video.category} • ${video.year}',
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
            // 播放按钮
            const Icon(
              Icons.play_circle_outline,
              color: AppTheme.netflixRed,
              size: 24,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInteractionInfo(BuildContext context) {
    // 只有在有互动的情况下才显示
    if (post.likeCount == 0 && post.commentCount == 0 && post.shareCount == 0) {
      return const SizedBox.shrink();
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(
            color: Colors.grey[850]!,
            width: 0.5,
          ),
          bottom: BorderSide(
            color: Colors.grey[850]!,
            width: 0.5,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (post.likeCount > 0)
            Text(
              '${post.likeCount}人点赞',
              style: TextStyle(
                color: Colors.grey[500],
                fontSize: 12,
              ),
            ),
          if (post.commentCount > 0)
            Text(
              '${post.commentCount}条评论',
              style: TextStyle(
                color: Colors.grey[500],
                fontSize: 12,
              ),
            ),
          if (post.shareCount > 0)
            Text(
              '${post.shareCount}人分享',
              style: TextStyle(
                color: Colors.grey[500],
                fontSize: 12,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        // 点赞按钮
        _buildActionButton(
          icon: post.isLiked
              ? Icons.favorite
              : Icons.favorite_border,
          label: '点赞',
          iconColor: post.isLiked ? AppTheme.netflixRed : Colors.grey,
          onTap: onLikeTap,
        ),
        // 评论按钮
        _buildActionButton(
          icon: Icons.chat_bubble_outline,
          label: '评论',
          onTap: onCommentTap,
        ),
        // 分享按钮
        _buildActionButton(
          icon: Icons.share,
          label: '分享',
          onTap: onShareTap,
        ),
      ],
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    Color? iconColor,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
        child: Row(
          children: [
            Icon(
              icon,
              color: iconColor ?? Colors.grey,
              size: 18,
            ),
            const SizedBox(width: 6),
            Text(
              label,
              style: TextStyle(
                color: Colors.grey[300],
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showPostOptionsDialog(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.cardColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部把手
              Container(
                width: 40,
                height: 4,
                margin: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.grey[600],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              // 选项列表
              ListTile(
                leading: const Icon(Icons.bookmark_border),
                title: const Text('收藏帖子'),
                onTap: () {
                  Navigator.pop(context);
                  // 收藏帖子
                },
              ),
              ListTile(
                leading: const Icon(Icons.person_outline),
                title: const Text('查看用户主页'),
                onTap: () {
                  Navigator.pop(context);
                  // 查看用户主页
                },
              ),
              ListTile(
                leading: const Icon(Icons.block),
                title: const Text('屏蔽此内容'),
                onTap: () {
                  Navigator.pop(context);
                  // 屏蔽内容
                },
              ),
              ListTile(
                leading: const Icon(Icons.report),
                title: const Text('举报'),
                onTap: () {
                  Navigator.pop(context);
                  // 举报
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }
}
